package cn.itsource.basic.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;
    //前置拦截器  -- 接收请求以后，执行目标方法之前
    /*
        fasle: 拦截
        true:  放行
        1.获取请求头 TOKEN
        2.使用token 去redis里面获取数据
        3.找不到，拦截 返回错误的信息
        4.找到，放行，刷新redis过期时间

     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求头 TOKEN
        String token = request.getHeader("TOKEN");
        if (token!=null){
            //2.使用token 去redis里面获取数据
            Object o = redisTemplate.opsForValue().get(token);
            if (o!=null){
                //刷新过去时间
                redisTemplate.opsForValue().set(token,o,30, TimeUnit.MINUTES);
                //放行
                return true;
            }
        }
        //设置响应头和字符编码
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();

        //返回错误的提示{"success":false,"message":"noAuth"}
        //响应数据
        out.println("{\"success\":false,\"message\":\"noAuth\"}");

        return false;
    }
}
